<template>
  <div style="padding: 20px;">
    <div class="topLocation">球员信息管理 / 球员管理</div>
    <div class="topTool">
      <div class="group">球员姓名：</div>
      <el-input v-model="searchName" placeholder="请输入球员姓名" style="margin-right: 50px;"></el-input>
      <div class="group">球员用户名：</div>
      <el-input v-model="searchUsername" placeholder="请输入球员用户名" style="margin-right: 50px;"></el-input>
      <div class="group">球员司职位置：</div>
      <el-select v-model="searchPosition" placeholder="请选择球员司职位置">
        <el-option label="控球后卫" value="控球后卫"></el-option>
        <el-option label="得分后卫" value="得分后卫"></el-option>
        <el-option label="小前锋" value="小前锋"></el-option>
        <el-option label="大前锋" value="大前锋"></el-option>
        <el-option label="中锋" value="中锋"></el-option>
        <el-option label="所有位置" value=""></el-option>
      </el-select>
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="success" :icon="Plus" @click="handleAdd">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelList" v-if="multipleSelection.length > 0">删除选中球员
      </el-button>
    </div>
    <el-table
        :data="playerData"
        :header-cell-style="{ background: '#f6f9fa'}"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="gender" label="性别"></el-table-column>
      <el-table-column prop="position" label="司职位置"></el-table-column>
      <el-table-column prop="phonenumber" label="手机号码"></el-table-column>
      <el-table-column prop="addtime" label="参加时间"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 添加球员的对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form.username" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age" type="number" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="司职位置">
          <el-select v-model="form.position" placeholder="请选择司职位置">
            <el-option label="控球后卫" value="控球后卫"></el-option>
            <el-option label="得分后卫" value="得分后卫"></el-option>
            <el-option label="小前锋" value="小前锋"></el-option>
            <el-option label="大前锋" value="大前锋"></el-option>
            <el-option label="中锋" value="中锋"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="form.phonenumber" autocomplete="off"/>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogOk">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";

const playerData = ref([]); // 球员数据
const currentPage = ref(1); // 当前页数
const pageSize = ref(5); // 每页显示条数
const total = ref(0); // 总记录数
const searchName = ref(''); // 球员姓名搜索关键字
const searchUsername = ref(''); // 球员用户名搜索关键字
const searchPosition = ref(''); // 球员司职位置搜索关键字

const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '无日期';
  const date = new Date(cellValue);
  if (isNaN(date.getTime())) {
    return '无效日期';
  }
  return date.toLocaleDateString();
};

// 组件挂载时加载数据
onMounted(() => {
  getData();
});

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/player/findByPage', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchName.value,
      username: searchUsername.value,
      position: searchPosition.value
    }
  }).then(response => {
    playerData.value = response.data.data.records;
    total.value = response.data.data.total;
  }).catch(error => {
    console.error(error);
  });
};

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '您确定要删除球员姓名为【' + row.name + '】的球员信息吗?',
      '危险操作'
  ).then(() => {
    delPlayer(row.id);
    ElMessage({
      type: 'success',
      message: '完成删除！',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    });
  });
};

// 删除请求
const delPlayer = (playerId) => {
  axios.delete(`http://localhost:8080/player/${playerId}`)
      .then(response => {
        getData(); // 删除成功后重新获取球员数据
      })
      .catch(error => {
        console.error(error);
      });
};

// 查询操作
const handleSearch = () => {
  const params = {
    name: searchName.value || null,
    username: searchUsername.value || null,
    position: searchPosition.value || null
  };
  axios.get('http://localhost:8080/player/search', { params })
      .then(response => {
        playerData.value = response.data.data;
        total.value= response.data.data.length; // 假设返回的是一个数组，直接取长度
      })
      .catch(error => {
        console.error(error);
        ElMessage.error('查询失败');
      });
};

// 字段排序
const handleSortChange = (sortData) => {
  const { prop, order } = sortData;
  playerData.value = playerData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

// 创建响应式变量multipleSelection，用于存储当前选中的数据行
let multipleSelection = ref([]);

// 处理表格行选中状态变化的方法，val是当前选中的数据行数组
const handleSelectionChange = (val) => {
  // 清空数组，确保每次更新都是最新选中状态
  multipleSelection.value = val.map(item => item.id); // 将选中的每一行数据的id存入multipleSelection数组中
};

// 批量删除操作
const handleDelList = () => {
  console.log('Selected player IDs:', multipleSelection.value); // 添加日志，确保选择的 player IDs 正确
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的球员！');
    return;
  }
  ElMessageBox.confirm(
      '您确定要删除选择的球员吗?',
      '危险操作'
  ).then(() => {
    axios.delete(`http://localhost:8080/player/batch`, { data: multipleSelection.value })
        .then(response => {
          getData();
          ElMessage.success('完成批量删除！');
        })
        .catch(error => {
          console.error('删除失败:', error); // 输出错误信息
          ElMessage.error('删除失败！');
        });
  }).catch(() => {
    ElMessage.info('取消删除！');
  });
};

// 弹窗相关变量
const dialogFormVisible = ref(false); // 控制弹窗显示
// 初始化表单数据结构，包括添加日期字段
const form = ref({
  id: '',
  name: '',
  username: '',
  password:'',
  age: '',
  gender: '男',
  position: '',
  phonenumber: '',
  addtime: new Date().toLocaleDateString() // 将当前日期设置为添加时间的初始值
});
const dialogType = ref('add'); // 初始化弹出框的类型为增加弹窗

// 添加球员按钮点击事件处理函数
const handleAdd = () => {
  dialogFormVisible.value = true;
  dialogType.value = 'add';
  // 设置表单默认值，包括添加时间
  form.value = {
    id: '',
    name: '',
    username: '',
    password:'',
    age: '',
    gender: '男',
    position: '',
    phonenumber: '',
    addtime: new Date().toLocaleDateString() // 设置为当前日期
  };
};

// 设置弹窗的标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增球员信息' : '编辑球员信息';
});

// 确定按钮点击事件处理函数
const dialogOk = () => {
  dialogFormVisible.value = false;
  if (dialogType.value === 'add') {
    addPlayer();
  } else {
    updatePlayer();
  }
};

// 添加球员信息函数
const addPlayer = () => {
  const newPlayer = { ...form.value };
  axios.post('http://localhost:8080/player', newPlayer)
      .then(response => {
        ElMessage.success('添加球员信息成功');
        getData(); // 在添加数据后重新获取数据
      })
      .catch(error => {
        ElMessage.error('添加球员信息失败');
        console.error(error);
      });
};

// 处理编辑按钮点击事件
const handleEdit = (row) => {
  form.value = { ...row };
  dialogType.value = 'edit';
  dialogFormVisible.value = true;
};

// 更新球员信息
const updatePlayer = () => {
  const playerId = form.value.id;
  const updatedPlayer = { ...form.value };
  axios.put(`http://localhost:8080/player/${playerId}`, updatedPlayer)
      .then(response => {
        ElMessage.success('修改球员信息成功');
        getData(); // 更新表格显示
      })
      .catch(error => {
        ElMessage.error('修改球员信息失败');
        console.error(error);
      });
};


</script>

<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px;     /* 设置字体大小为 14px */
}
</style>

